package com.lagou.gateway.resolver;

import com.lagou.gateway.constants.GatewayKnownHeader;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class AuthorizationKeyResolver implements KeyResolver {
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        return Mono
                .just(exchange.getRequest())
                .map(request -> {
                    String remoteHost = request.getRemoteAddress().getHostName();
                    String authorizationToken = request.getHeaders().getFirst(GatewayKnownHeader.AUTHORIZATION_TOKEN);
                    return String.format("%s_%s",
                            (remoteHost == null ? "host" : remoteHost),
                            authorizationToken == null ? "authorization" : authorizationToken);
                });
    }
}
